import { constantRoutes } from '@/router'
import { getRoutes, MultidimensionalToOnedimensional, filterAsyncRoutes } from '@/utils/route-handle'
const getDefaultState = () => {
  return {
    routes: [],
    addRoutes: []
  }
}
const state = getDefaultState()

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = [
      ...constantRoutes,
      ...routes
    ]
  },
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  }
}

const actions = {
  generateRoutes({ commit }, { asyncRoutes, resource }) {
    debugger
    return new Promise(resolve => {
      const routesMap = getRoutes(resource)
      const filterRoutesMap = MultidimensionalToOnedimensional(routesMap)
      const accessedRoutes = [
        ...filterAsyncRoutes(asyncRoutes, filterRoutesMap),
        { path: '*', redirect: '/404', hidden: true }
      ]
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },
  resetState({ commit }) {
    return new Promise(resolve => {
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
